# -*- coding:utf-8 -*-

import urllib
import urllib2
import cookielib
import httplib
import json
from conf import settings

"""
    zwx 2017-12-28
    主要用来封装一些基础的post、get请求、以及返回内容处理
"""

class basic_http_request():
    #判断接口地址是否返回200
    def http_code(self,url):
        code = urllib.urlopen(url).getcode()
        return code

    #定义基础的post请求
    def http_basic_post(self,interface_url,interface_param):
        #根据传入的dict参数封装成http可以使用的类型
        interface_data = urllib.urlencode(interface_param)
        #进行接口请求
        try:
            request = urllib2.Request(interface_url, interface_data)
            response = urllib2.urlopen(request)
            # 请求结果打印
            response_result = response.read()
            print response_result
            return response_result
        #进行异常捕获
        except urllib2.HTTPError, interface_connect_error:
            print interface_connect_error
        except urllib2.URLError, interface_connect_error:
            print interface_connect_error.reason
        if interface_connect_error.code == 404:
            print u'接口连接失败,接口请求地址错误'
            print u'接口地址：' + interface_url

        elif interface_connect_error.code == 500:
            print u'接口连接失败，接口参数错误;'
            print u'接口地址为：' + interface_url
            print u'接口参数为' + str(interface_param)
        else:
            print u'接口连接错误，错误原因未知'

        return interface_connect_error

    #统一http的请求
    def http_request(self,interface_url,interface_param,type):
        result = ''
        if type == 'POST':
            result = self.http_basic_post(interface_url,interface_param)
        elif type =='GET':
            result = self.http_basic_post(interface_url,interface_param)
        return result

    #对返回结果进行处理，获取到当前的返回状态
    def response_status(self,response_infor):
        #先把返回结果处理成字典表格式
        response_dict = json.loads(response_infor)
        #根据字典表的内容，获取到resultInfo 信息
        response_resultInfo = response_dict['resultInfo']
        print response_resultInfo
        print type(response_resultInfo)
        print response_resultInfo['success']
        return response_resultInfo['success']

    #对返回结果进行处理，获取到当前的返回状态
    def response_body_data(self,response_infor):
        #先把返回结果处理成字典表格式
        response_dict = json.loads(response_infor)
        #根据字典表的内容，获取到resultInfo 信息
        response_resultInfo = response_dict['resultInfo']
        response_data = response_resultInfo['data']
        print response_data
        print len(response_data)
        return response_data

    #登录写入cookie做为公用方法
    def login_cookie_save(self,login_param):
        #初始化 cookie 数据
        cookie = cookielib.MozillaCookieJar(settings.cookie_file)
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        #初始化登录参数
        login_url = 'http://192.168.101.14:8080/eUrbanMIS/login/validpassword'
        login_data = urllib.urlencode(login_param)
        #进行登录保存cookie
        opener.open(login_url, login_data)
        cookie.save(ignore_discard=True, ignore_expires=True)

    #从文件中读取cookie
    def get_cookie_fromFile(self):
        # 创建MozillaCookieJar实例对象
        cookie = cookielib.MozillaCookieJar()
        # 从文件中读取cookie内容到变量
        cookie.load(settings.cookie_file, ignore_discard=True, ignore_expires=True)
        return cookie

    #对结果进行判断，判断接口的响应结果是否为404 500等错误页面
    def interface_connect_stat(self,response_infor):
        print u'对接口的结果进行判断，查看接口是否可以正常连接'
        response_dict = json.loads(response_infor)
        if str(type(response_dict)) == "<class 'urllib2.HTTPError'>":
            if response_dict['code'] == 404:
                print 404
    #测试
    def test(self):
        cookie = self.get_cookie_fromFile()
        # 请求参数
        values = {}
        values['taskListID'] = '29'
        values['currentPage'] = '1'
        values['numPerPage'] = '10'
        get_data = urllib.urlencode(values)
        # 请求接口
        url = 'http://192.168.101.14:8080/eUrbanMIS/home/bizbase/tasklist/gethumantasklistdata'
        get_url = url + '?' + get_data
        # 创建请求的request
        request = urllib2.Request(get_url)
        # 利用urllib2的build_opener方法创建一个opener
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
        response = opener.open(request)
        print response.read()

if __name__ == '__main__':
    print "utils test"
    login_param = {'userName': 'egova', 'ip': '', 'browserVersion': 'chrome/61.0.3163.100', 'password': '', 'osVersion': 'Win10/64'}
    reguest_interface = basic_http_request()
    response = reguest_interface.http_basic_post('test','test')
    print response
    print type(response)
    print str(type(response)) == "<class 'urllib2.HTTPError'>"
    reguest_interface.interface_connect_stat(response)
    # reguest_interface.response_status(response)
    # reguest_interface.response_body_data(response)
    # reguest_interface.login_cookie_save(login_param)
    # reguest_interface.test()
